import threading

from rclpy.clock import ROSClock
from rclpy.qos import DurabilityPolicy, QoSProfile
from std_msgs.msg import Int32

from ros2webserver_msgs.msg import ConnectedClient, ConnectedClients


class ClientManager:
    def __init__(self, node_handle):
        qos = QoSProfile(
            depth=1,
            durability=DurabilityPolicy.TRANSIENT_LOCAL,
        )
        
        # Publisher for number of connected clients
        self._client_count_pub = node_handle.create_publisher(
            Int32, "client_count", qos_profile=qos
        )
        # Publisher for connected clients
        self._conn_clients_pub = node_handle.create_publisher(
            ConnectedClients, "connected_clients", qos_profile=qos
        )

        self._lock = threading.Lock()
        self._client_count = 0
        self._clients = {}
        self.__publish()

    def __publish(self):
        msg = ConnectedClients()
        msg.clients = list(self._clients.values())
        self._conn_clients_pub.publish(msg)
        self._client_count_pub.publish(Int32(data=len(msg.clients)))

    def add_client(self, client_id, ip_address):
        with self._lock:
            client = ConnectedClient()
            client.ip_address = ip_address
            client.connection_time = ROSClock().now().to_msg()
            self._clients[client_id] = client
            self.__publish()

    def remove_client(self, client_id, ip_address):
        with self._lock:
            self._clients.pop(client_id, None)
            self.__publish()
